package com.hxd.otc.module.convenience.activity;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.module.convenience.adapter.ChooseHydropowerCityAdapter;
import com.hxd.otc.module.convenience.bean.ChooseHydropowerCityBean;
import com.hxd.otc.module.convenience.bean.NorGoodsBean;
import com.hxd.otc.module.convenience.contract.ChooseHydropwerCityContract;
import com.hxd.otc.module.convenience.presenter.ChooseHydropwerCityPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.LocationService;
import com.hxd.otc.widget.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.List;

import butterknife.BindView;

public class ChooseHydropowerCityActivity extends PermissionActivity<ChooseHydropwerCityPresenter> implements ChooseHydropwerCityContract.View {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    View errorView;

    View notDataView;

    TextView tvRefresh;

    ChooseHydropowerCityAdapter mAdapter;
    NorGoodsBean bean;

    int pageNo;
    int pageSize = 15;
    boolean isLoadMore;

    OptionsPickerView pvOptions;
    String province, city;
    LocationService locationService;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_choose_hydropower_city;
    }

    @Override
    protected void initView() {
        bean = (NorGoodsBean) getIntent().getExtras().getSerializable(HydropwerDetailActivity.NORGOODSBEAN);
        titleBar.setTitleText(getString(R.string.institutional_choice, bean.getGoodsName()));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (titleBar.getRightText().getText().toString().equals(getString(R.string.choose_city))) {
                    showToast(getString(R.string.choose_city));
                    mRefreshLayout.finishLoadMore();
                    return;
                }
//                isLoadMore = true;
//                pageNo = pageNo + 1;
                mPresenter.getLocation(province, city, bean.getModuleCode());
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (titleBar.getRightText().getText().toString().equals(getString(R.string.choose_city))) {
                    showToast(getString(R.string.choose_city));
                    mRefreshLayout.finishRefresh();
                    return;
                }
                isLoadMore = false;
                pageNo = 0;
                mPresenter.getLocation(province, city, bean.getModuleCode());
            }
        });

        notDataView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) recyclerView.getParent(), false);
        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) recyclerView.getParent(), false);
        tvRefresh = errorView.findViewById(R.id.tv_refresh);
        tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshLayout.autoRefresh(0, 10, 1);
            }
        });
    }

    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new ChooseHydropowerCityAdapter();
            mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Bundle bundle = new Bundle();
                    mAdapter.getItem(position).city = city;
                    mAdapter.getItem(position).province = province;
                    bundle.putSerializable("ChooseHydropowerCityBean", mAdapter.getItem(position));
                    bundle.putSerializable(HydropwerDetailActivity.NORGOODSBEAN, bean);
                    $startActivity(HydropwerPaymentInfActivity.class, bundle);
                }
            });
        }
        recyclerView.setAdapter(mAdapter);
    }


    @Override
    protected void initData() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                location();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {

            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
            }

            @Override
            public void onLowVersion() {
                location();
            }
        }, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);

        initAdapter();
        mPresenter.doGetProvince(getAssets(), Constant.Login.CHOOSE_CITY_PATH);
    }

    private void location() {
        locationService = new LocationService(this);
        locationService.start(new LocationService.locationCallBack() {
            @Override
            public void getAddress(String sProvince, String sCity) {
                province = sProvince;
                city = sCity;
                if (province.substring(province.length() - 1, province.length()).equals("省")) {
                    province = province.substring(0, province.length() - 1);
                }
                if (city.substring(city.length() - 1, city.length()).endsWith("市")) {
                    city = city.substring(0, city.length() - 1);
                }
                titleBar.getRightText().setText(city);
                mRefreshLayout.autoRefresh(0, 10, 1);
            }
        });
    }

    @Override
    protected void initEvent() {
        titleBar.setOnTitleBarItemClickListener(new TitleBar.OnTitleBarItemClickListener() {
            @Override
            public void onBack(View v) {
                finish();
            }

            @Override
            public void onRight(View v) {
                ShowPickerView();
            }
        });
    }

    private void ShowPickerView() {// 弹出选择器
        if (mPresenter.getOptions1Items().size() <= 0) {
            return;
        }

        if (pvOptions == null) {
            pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    province = mPresenter.getOptions1Items().get(options1).getName();
                    city = mPresenter.getOptions2Items().get(options1).get(options2);
                    if (province.substring(province.length() - 1, province.length()).equals(getString(R.string.province))) {
                        province = province.substring(0, province.length() - 1);
                    }
                    if (city.substring(city.length() - 1, city.length()).endsWith(getString(R.string.city))) {
                        city = city.substring(0, city.length() - 1);
                    }
                    titleBar.getRightText().setText(city);
                    mRefreshLayout.autoRefresh(0, 10, 1);
                }
            })

                    .setTitleText(getString(R.string.city_selection))
                    .setDividerColor(Color.BLACK)
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(20)
                    .setOutSideCancelable(true)// default is true
                    .build();

            pvOptions.setPicker(mPresenter.getOptions1Items(), mPresenter.getOptions2Items());//三级选择器
        }
        pvOptions.show();
    }

    @Override
    protected ChooseHydropwerCityPresenter createPresenter() {
        return new ChooseHydropwerCityPresenter(this);
    }

    @Override
    public void onSetAdapter(List<ChooseHydropowerCityBean> list) {

        if (list == null) {
            return;
        }


        if (isLoadMore) {
            mAdapter.addData(list);
        } else {
            if (list.size() <= 0) {
                mAdapter.setEmptyView(notDataView);
            }
            mAdapter.setNewData(list);
        }
    }

    @Override
    public void onShowNoMore() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            locationService.stop();
            locationService.onDestory();
            locationService = null;
        }

    }

    @Override
    public void onError(int code) {
        super.onError(code);
        if (!isLoadMore)
            mAdapter.setEmptyView(errorView);
    }
}
